package com.hzit.user.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.user.mapper.UserMapper;
import com.hzit.user.service.IUserService;
import com.hzit.user.vo.UserVo;
import com.ruoyi.common.core.constant.HzitCodeMessageTopicConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.MyFeignException;
import com.ruoyi.system.api.RemoteManagerService;
import com.ruoyi.system.api.domain.Brand;
import com.ruoyi.system.api.domain.User;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private RocketMQTemplate mqTemplate;
	@Autowired
	private RemoteManagerService managerService;

	//1.  生成手机验证码并发送给第三方
	@Override
	public void createCode(String phone) {
		//1.1 生成四位数字组成的随机数
		String s = RandomUtil.randomNumbers(4);
		//1.2 将生成的随机验证码放到redis中
		redisTemplate.opsForValue().set(phone,s,10, TimeUnit.HOURS);  //  保存到redis中是10小时
		//1.3 发送手机验证码及其它信息到第三方
		Map map = new HashMap<>();
		map.put("phone",phone);
		map.put("code",s);
		mqTemplate.convertAndSend(HzitCodeMessageTopicConstants.TOPIC,map);

	}

	//2. 添加用户
	@Override
	public boolean add(UserVo vo) {
		//2.1 校验验证码
		String code = vo.getCode();
		String s = redisTemplate.opsForValue().get(vo.getPhone());
		if(code.equals(s)){ // 如果验证码判断相等，就添加用户到数据库
			//2.2  准备要添加的数据
			User user = new User();
			user.setCreated(LocalDateTime.now());
			user.setUpdated(LocalDateTime.now());
			user.setUsername(vo.getUsername());
			String md5Pwd = SecureUtil.md5(vo.getPassword());       // 将密码经过md5加密
			user.setPassword(md5Pwd);
			//2.3 添加用户到数据库中
			this.save(user);
			return true;
		}
		return false;
	}

	//1. 本地添加用户，远程添加品牌
	@Override
	@GlobalTransactional
	@Transactional
	public void addUserAndBrand() {
		//1.1 本地添加用户
		User user = new User();
		user.setUsername("张三");
		user.setPassword("123456");
		user.setCreated(LocalDateTime.now());
		user.setUpdated(LocalDateTime.now());
		this.save(user);

		//1.2 远程调用添加品牌
		R r = managerService.addBrand();
		System.out.println("r = " + r);
		if (r.getCode() == 500) {
			throw new MyFeignException(r.getCode(),"出现出远程调用异常！");
		}
	}

	// 2. 远程调用查询品牌列表
	@Override
	public R<List<Brand>> findBrands() {
		return managerService.findAllBrands();
	}
}
